package com.qd.aliyun.service;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.cdqidi.exception.ApiException;
import com.qd.system.sms.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 阿里云短信发送
 *
 * @author sjk
 */
@Service
@Slf4j
public class AliYunSmsServiceImpl implements ISmsService {

    @Resource
    @Qualifier(value = "aliyunSmsClient")
    private Client client;

    @Override
    public String sendSms(String phoneNumbers, String templateCode, String templateParam, String signName) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumbers)
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam)
                .setSignName(signName);
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if (sendSmsResponse.getStatusCode().equals(HttpStatus.OK.value())) {
                SendSmsResponseBody body = sendSmsResponse.getBody();
                if ("OK".equals(body.code)) {
                    return sendSmsResponse.getBody().getBizId();
                } else {
                    log.error("阿里云发送短信异常,code: {},message: {}", sendSmsResponse.getBody().getCode(), sendSmsResponse.getBody().getMessage());
                    throw new ApiException("发送短信异常[" + sendSmsResponse.getBody().getMessage() + "]");
                }
            } else {
                throw new ApiException("发送短信异常");
            }
        } catch (Exception e) {
            log.error("阿里云发送短信异常", e);
            throw new ApiException(e);
        }
    }


}
